//
//  CZUserAccount.swift
//  swiftweibo1.0
//
//  Created by 许建安 on 15/11/26.
//  Copyright © 2015年 itcast. All rights reserved.
//


import UIKit

//将对象归档到沙盒
class CZUserAccount: NSObject, NSCoding {
    
    //用于调用access_token,接口获取授权后的access token.
    var access_token : String? //创建一个接口属性
    
    //access_token的生命周期，单位是秒数。在KVC字典转模型基本数据类型要设置初始值
    var expires_in: NSTimeInterval = 0 {
        didSet {
            //设置过期时间
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    
    ///保存过期时间NSDate
    var expiresDate: NSDate?
    
    ///当前授权用户的UID
    var uid: String?
    
    ///字典转模型
    init(dict: [String: AnyObject]) {
        super.init()
        //KVC 字典转模型
        setValuesForKeysWithDictionary(dict)
    }
    
    //保存路径 static 类方法也可以访问，对象方法访问需要使用类名，属性名
    static let plistPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! + "/account.plist"
    
    //保存账户信息到沙盒
    func saveAccout() {
        //归档 当前类
        NSKeyedArchiver.archiveRootObject(self, toFile: CZUserAccount.plistPath)//把东西存到路径中
    }
    
    //读取 保存在沙盒中的账号信息
    class func loadUserAccount() -> CZUserAccount? {
        //解档，如果有对象需要判断是否过期
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(plistPath) as? CZUserAccount {
            //如果能来到这里说明解档了一个对象，判断是否过期
            if account.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
                print("没有过期")
                return account
            }
        }
        return nil
    }
    
    //解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        
    }
    
    //归档
    func encodeWithCoder(aCoder: NSCoder)
    {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
    }
    
    ///当KVC字典的key在模型中找不到对应的属性
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {

    }
    
    ///打印对象的信息
    override var description: String {
        return "access_token: \(access_token), expires_in:\(expires_in), uid = \(uid), expiresDate:\(expiresDate)"
    }
    
    
    
}









